import React, { FC, createRef, useEffect } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { IRoute } from '../../router';
import logo from '@/assets/logo.png';
import avatar from '@/assets/avatar.jpg';
import './index.less';

interface IProps {
  items: IRoute[];
}

export const Navbar: FC<IProps> = ({
  items,
}) => {

  const theLocation = useLocation();
  const nav = createRef<HTMLUListElement>();
  const slidebar = createRef<HTMLDivElement>();

  // 修改 slidebar 的样式
  useEffect(() => {
    if (!items.some(route => route.path === theLocation.pathname)) {
      slidebar.current!.style.display = 'none';
      return;
    }
    slidebar.current!.style.display = 'block';
    const children = Array.from(nav.current!.children);
    for (const child of children) {
      if (child.nodeType !== 1) break;
      if (child.nodeName !== 'A') break;
      if ((child as HTMLAnchorElement).href.endsWith(theLocation.pathname)) {
        const anchor: HTMLAnchorElement = (child as HTMLAnchorElement);
        const maxWidth = anchor.offsetWidth;
        const left = anchor.offsetLeft;
        slidebar.current!.style.maxWidth = maxWidth + 10 + 'px';
        slidebar.current!.style.left = left - 5 + 'px';
        break;
      }
    }
  }, [theLocation.pathname]);

  return (
    <nav className='navbar'>
      <a className='logo' href={ location.origin }>
        <img src={ logo } alt="全栈导航" />
      </a>
      <ul className='nav' ref={ nav }>
        {
          items.map(({ path, title }) =>
            <Link key={ title } to={ path }>{ title }</Link>
          )
        }
        <div className='slidebar' ref={ slidebar }></div>
      </ul>
      <div className='nav-end'>
        <Link className='avatar' to="/center/info">
          <img src={ avatar } alt="" />
        </Link>
      </div>
    </nav>
  );
};
